<script setup lang='ts' name="role-auth-user">
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { SearchForm, SearchTable } from '@fl/components'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { cancelAllAuthUser, cancelAuthUser, getAuthUserList, getUnauthUseList, saveConfigUser } from '@fl/api/sys-set-api'

const props = withDefaults(defineProps<{
    modelValue: boolean
    roleId?: string
}>(), {
    modelValue: false,
    roleId: '',
})
const emits = defineEmits(['update:modelValue'])

const { roleId, modelValue } = toRefs(props)

const route = useRoute()
// const roleId = route.params.id as string
const { go } = useRouter()
const initialState = {
    userName: '',
    phonenumber: '',
}
const state = ref(cloneDeep(initialState))
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const columns = ref([
    {
        label: '用户名称',
        prop: 'userName',
        valueType: 'copy',
    },
    {
        label: '手机号码',
        prop: 'phonenumber',
        valueType: 'copy',
    },
])
const isLoading = ref(false)
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'userName', minWidth: 90, title: '用户名称' },
        { field: 'nickName', minWidth: 90, title: '用户昵称' },
        { field: 'email', minWidth: 80, title: '邮箱' },
        { field: 'phonenumber', minWidth: 150, title: '手机' },
        { field: 'status', minWidth: 100, slots: { default: 'status' }, title: '状态' },
        { field: 'createTime', title: '创建时间', width: 300 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', minWidth: 220 },
    ],
})
const list = ref([])
const visible = ref(false)
const dialogInitialState = {
    userName: '',
    phonenumber: '',
}
const dialogState = ref(cloneDeep(dialogInitialState))
const dialogColumns = ref([
    {
        label: '用户名称',
        prop: 'userName',
        valueType: 'copy',
    },
    {
        label: '手机号码',
        prop: 'phonenumber',
        valueType: 'copy',
    },
])
const selectUsers = ref('')
const dialogInitialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const dialogTablePage = ref(cloneDeep(dialogInitialPage))
const dialogIsLoading = ref(false)
const dialogGridOptions = reactive<VxeGridProps>({
    columns: [
        { type: 'checkbox', width: 50 },
        { field: 'userName', minWidth: 90, title: '用户名称' },
        { field: 'nickName', minWidth: 90, title: '用户昵称' },
        { field: 'email', minWidth: 80, title: '邮箱' },
        { field: 'phonenumber', minWidth: 90, title: '手机' },
        { field: 'status', minWidth: 100, slots: { default: 'status' }, title: '状态' },
        { field: 'createTime', title: '创建时间', width: 300 },
    ],
})
const dialogList = ref([])
const userIds = ref('')

function close() {
    emits('update:modelValue', false)
}

getListData()

function getListData() {
    isLoading.value = true
    getAuthUserList({
        ...state.value,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
        roleId,
    }).then((res) => {
        isLoading.value = false
        list.value = res.rows
        tablePage.value.total = res.total
    }).catch(() => {
        isLoading.value = false
    })
}

function submitSearch(values) {
    if (values) {
        state.value = values
        getListData()
    }
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    getListData()
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    getListData()
}

function checkboxChange(values) {
    const ids = values.records.map(item => item.userId)
    selectUsers.value = ids.join()
}

function dialogGetListData() {
    dialogIsLoading.value = true
    getUnauthUseList({
        ...dialogState.value,
        pageNum: dialogTablePage.value.currentPage,
        pageSize: dialogTablePage.value.pageSize,
        roleId,
    }).then((res) => {
        dialogIsLoading.value = false
        dialogList.value = res.rows
        dialogTablePage.value.total = res.total
    }).catch(() => {
        dialogIsLoading.value = false
    })
}

function dialogSubmitSearch(values) {
    if (values) {
        dialogState.value = values
        dialogGetListData()
    }
}

function dialogResetSearch() {
    dialogState.value = cloneDeep(dialogInitialState)
    dialogGetListData()
}

async function addAuthUser() {
    await dialogGetListData()
    visible.value = true
}
const handleDialogPageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    getListData()
}

function dialogCheckboxChange(values) {
    const ids = values.records.map(item => item.userId)
    userIds.value = ids.join()
}

function confirmAddAuthUser() {
    if (!userIds.value) {
        ElMessage.error('请选择要分配的用户')
        return
    }
    saveConfigUser({
        roleId,
        userIds: userIds.value,
    }).then(() => {
        ElMessage.success('分配成功')
        visible.value = false
        getListData()
    })
}

function cancelAuthUserHoldler(row) {
    ElMessageBox.confirm(
        row.userId ? `您确定要取消该用户『${row.userName}』角色吗？` : '您确定取消要所勾选的角色吗？',
        row.userId ? '系统提示' : '批量取消授权',
        {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning',
        },
    )
        .then(() => {
            if (row.userId) {
                cancelAuthUser({
                    roleId,
                    userId: row.userId,
                }).then(() => {
                    ElMessage.success('操作成功')
                    getListData()
                })
            }
            else {
                cancelAllAuthUser({
                    roleId,
                    userIds: selectUsers.value,
                }).then(() => {
                    ElMessage.success('操作成功')
                    getListData()
                })
            }
        }).catch(() => {
            ElMessage({
                message: '取消操作',
                type: 'info',
            })
        })
}

/**
 * methods end
 */
</script>

<template>
    <el-dialog v-model="modelValue"
               title="提示"
               @close="close"
    >
        <div class="role-auth-user">
            <ElCard class="mb-20"
                    shadow="never"
            >
                <SearchForm v-bind="state"
                            :columns="columns"
                            submit-text="搜索"
                            @reset="resetSearch"
                            @submit="submitSearch"
                />
            </ElCard>

            <ElCard shadow="never">
                <SearchTable v-bind="gridOptions"
                             v-model:pager="tablePage"
                             :loading="isLoading"
                             :data="list"
                             @page-change="handlePageChange"
                             @checkbox-change="checkboxChange"
                >
                    <template #toolbar_buttons>
                        <el-button plain
                                   type="primary"
                                   @click="addAuthUser"
                        >
                            添加用户
                        </el-button>

                        <el-button plain
                                   type="primary"
                                   @click="cancelAuthUserHoldler({})"
                        >
                            批量取消授权
                        </el-button>
                    </template>

                    <template #enableStatus="{ row }">
                        <el-switch v-model="row.enableStatus"
                                   :active-value="1"
                                   :inactive-value="0"
                        />
                    </template>

                    <template #status="{ row }">
                        <el-tag :type="['success', 'danger'][row.status as string]">
                            {{ ['正常', '停用'][row.status] }}
                        </el-tag>
                    </template>

                    <template #operate="{ row }">
                        <div class="operate-btns">
                            <el-button type="primary"
                                       text
                                       @click="cancelAuthUserHoldler(row)"
                            >
                                取消授权
                            </el-button>
                        </div>
                    </template>
                </SearchTable>
            </ElCard>

            <el-dialog v-model="visible"
                       title="选择用户"
                       width="1080"
                       class="add-user-dialog"
            >
                <SearchForm v-bind="dialogState"
                            :columns="dialogColumns"
                            submit-text="搜索"
                            @reset="dialogResetSearch"
                            @submit="dialogSubmitSearch"
                />

                <SearchTable v-bind="dialogGridOptions"
                             v-model:pager="dialogTablePage"
                             :loading="dialogIsLoading"
                             :data="dialogList"
                             @page-change="handleDialogPageChange"
                             @checkbox-change="dialogCheckboxChange"
                >
                    <template #status="{ row }">
                        <el-tag :type="['success', 'danger'][row.status as string]">
                            {{ ['正常', '停用'][row.status] }}
                        </el-tag>
                    </template>
                </SearchTable>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="visible = false">取 消</el-button>

                        <el-button type="primary"
                                   @click="confirmAddAuthUser"
                        >确 定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.role-auth-user {
    :deep(.add-user-dialog) {
        .vxe-grid {
            height: calc(100vh - 272px);
            overflow-y: auto;
        }
    }
}
</style>
